//
// Created by Administrator on 2024/12/28.
//

#ifndef NETWORKCOMPONENT_DATASTREAM_H
#define NETWORKCOMPONENT_DATASTREAM_H

#include <iostream>
#include<vector>
#include<string>
#include<list>
#include<set>
#include<map>
#include<unordered_map>
#include <algorithm>
#include "Serializable.h"

/*
 * @brief:cpp实现序列化和反序列化
 * */
class DataStream
{
public:
    //序列化和反序列化的数据类型
    enum DataType
    {
        BOOL=0,
        CHAR,
        INT16,
        INT32,
        INT64,
        FLOAT,
        DOUBLE,
        STRING,
        VECTOR,
        LIST,
        SET,
        MAP,
        UNORDEREDMAP,
        CUSTOME //类或者结构体
    };

    //字节序大小端
    enum ByteOrder
    {
        BigEndian,//大端
        LittleEndian//小端
    };

    DataStream();
    ~DataStream();
    //缓冲区容量扩充
    void reserve(int len);
    //基础数据类型序列化数据
    void write(const char*data,int len);
    void write(bool value);
    void write(char value);
    void write(int16_t value);
    void write(int32_t value);
    void write(int64_t value);
    void write(float value);
    void write(double value);
    void write(const char *value);
    void write(const std::string &value);
    //STL类型的序列化
    template<typename T>
    void write(const std::vector<T>& value);

    template<typename T>
    void write(const std::list<T> &value);

    template<typename K,typename V>
    void write(const std::map<K,V> &value);

    template<typename T>
    void write(const std::set<T> &value);

    template<typename K,typename V>
    void write(const std::unordered_map<K,V>& value);

    //自定义类或者结构体序列化
    void write(const Serializable &value);

    template<typename T,typename ...Args>
    void write_args(const T& value,const Args & ...args);
    void write_args();


    //基础数据类型反序列化
    bool read(bool &value);
    bool read(char &value);
    bool read(int16_t &value);
    bool read(int32_t &value);
    bool read(int64_t &value);
    bool read(float &value);
    bool read(double &value);
    bool read(std::string &value);

    //STL类型的反序列化
    template<typename T>
    bool read(std::vector<T> &value);

    template<typename T>
    bool read(std::list<T> &value);

    template<typename K,typename V>
    bool read(std::map<K,V> &value);

    template<typename T>
    bool read(std::set<T> &value);

    template<typename K,typename V>
    bool read(std::unordered_map<K,V> &value);

    //自定义类或者结构体的反序列化
    bool read(Serializable &value);

    template<typename T,typename ...Args>
    bool read_args(T &value,Args & ...args);
    bool read_args();


    DataStream & operator << (bool value);
    DataStream & operator << (char value);
    DataStream & operator << (int16_t value);
    DataStream & operator << (int32_t value);
    DataStream & operator << (int64_t value);
    DataStream & operator << (float value);
    DataStream & operator << (double value);
    DataStream & operator << (const char* value);
    DataStream & operator << (const std::string& value);
    DataStream & operator << (const Serializable &value);

    template<typename T>
    DataStream & operator << (const std::vector<T> &value);
    template<typename T>
    DataStream & operator << (const std::list<T> &value);
    template<typename K,typename V>
    DataStream & operator << (const std::map<K,V> &value);
    template<typename T>
    DataStream & operator << (const std::set<T> &value);
    template<typename K,typename V>
    DataStream & operator << (const std::unordered_map<K,V> &value);



    DataStream & operator >> (bool &value);
    DataStream & operator >> (char &value);
    DataStream & operator >> (int16_t &value);
    DataStream & operator >> (int32_t &value);
    DataStream & operator >> (int64_t &value);
    DataStream & operator >> (float &value);
    DataStream & operator >> (double &value);
    DataStream & operator >> (std::string& value);
    DataStream & operator >> (Serializable& value);

    template<typename T>
    DataStream & operator >> (std::vector<T> &value);
    template<typename T>
    DataStream & operator >> (std::list<T> &value);
    template<typename K,typename V>
    DataStream & operator >> (std::map<K,V> &value);
    template<typename T>
    DataStream & operator >> (std::set<T> &value);
    template<typename K,typename V>
    DataStream & operator >> (std::unordered_map<K,V> &value);

    int size()const;
    void show();
    //获取缓冲区DataStream的数据类型
    bool readType(char *type,int len);
    //识别计算机大小端
    ByteOrder getByteOrder();
    char* data();

private:
    //存放数据的缓冲区
    std::vector<char>_buffer;
    //当前索引位置
    int _pos;
    ByteOrder _byteOrder;
};

template<typename T>
void DataStream::write(const std::vector<T> &value)
{
    char type = DataType::VECTOR;
    write((char *)&type,sizeof(char));
    if(value.empty())
    {
        std::runtime_error("value is empty");
    }

    int len = value.size();
    write(len);
    // 预分配缓冲区空间，避免多次扩容
    _buffer.reserve(_buffer.size() + len * sizeof(T));
    // 序列化向量中的每个元素
    for(const auto &element : value)
    {
        write(element);
    }
}

template<typename T>
void DataStream::write(const std::list<T> &value)
{
    char type = DataType::LIST;
    write((char *)&type,sizeof(char));
    if(value.empty())
    {
        std::runtime_error("value is empty");
    }

    int len = value.size();
    write(len);
    // 预分配缓冲区空间，避免多次扩容
    _buffer.reserve(_buffer.size() + len * sizeof(T));
    // 序列化向量中的每个元素
    for(const auto &element : value)
    {
        write(element);
    }
}

template<typename K, typename V>
void DataStream::write(const std::map<K, V> &value)
{
    char type = DataType::MAP;
    write((char *)&type,sizeof(char));
    if(value.empty())
    {
        std::runtime_error("value is empty");
    }
    int len = value.size();
    write(len);
    // 预分配缓冲区空间，避免多次扩容
    _buffer.reserve(_buffer.size() + len * (sizeof(K) + sizeof(V)));
    // 序列化map中的每个键值对
    for (const auto &pair : value)
    {
        write(pair.first);
        write(pair.second);
    }
}

template<typename T>
void DataStream::write(const std::set<T> &value)
{
    char type = DataType::SET;
    write((char *)&type,sizeof(char));
    if(value.empty())
    {
        std::runtime_error("value is empty");
    }

    int len = value.size();
    write(len);
    // 预分配缓冲区空间，避免多次扩容
    _buffer.reserve(_buffer.size() + len * sizeof(T));
    // 序列化集合中的每个元素
    for (const auto &element : value)
    {
        write(element);
    }
}

template<typename K, typename V>
void DataStream::write(const std::unordered_map<K, V> &value)
{
    char type = DataType::UNORDEREDMAP;
    write((char *)&type,sizeof(char));
    if(value.empty())
    {
        std::runtime_error("value is empty");
    }
    int len = value.size();
    write(len);
    // 预分配缓冲区空间，避免多次扩容
    _buffer.reserve(_buffer.size() + len * (sizeof(K) + sizeof(V)));
    // 序列化map中的每个键值对
    for (const auto &pair : value)
    {
        write(pair.first);
        write(pair.second);
    }
}


template<typename T>
bool DataStream::read(std::vector<T> &value)
{
    value.clear();
    //检测缓冲区是否越界
    if(_pos >= _buffer.size())
    {
        std::cerr << "Error: Buffer overflow during deserialization.\n";
        return false;
    }
    if(_buffer[_pos] != DataType::VECTOR)
    {
        std::cerr<<"unserialization is not vector\n";
        return false;
    }
    _pos++;
    int len;
    if(!read(len))
    {
        std::cerr<<"Error:Failed to read vector length\n";
        return false;
    }

    // 预分配内存，避免多次扩容
    value.reserve(len);
    for(int i=0;i<len;i++)
    {
        T v;
        if(!read(v))
        {
            std::cerr << "Error: Failed to read vector element at index " << i << ".\n";
            value.clear();
            return false;
        }
        // 使用移动语义减少拷贝开销
        value.emplace_back(std::move(v));
    }
    return true;
}

template<typename T>
bool DataStream::read(std::list<T> &value)
{
    value.clear();
    //检测缓冲区是否越界
    if(_pos >= _buffer.size())
    {
        std::cerr << "Error: Buffer overflow during deserialization.\n";
        return false;
    }
    if(_buffer[_pos] != DataType::LIST)
    {
        std::cerr<<"unserialization is not list\n";
        return false;
    }
    _pos++;
    int len;
    if(!read(len))
    {
        std::cerr<<"Error:Failed to read list length\n";
        return false;
    }
    value.clear(); // 再次清空以确保状态一致
    for(int i=0;i<len;i++)
    {
        T v;
        if(!read(v))
        {
            std::cerr << "Error: Failed to read list element at index " << i << ".\n";
            value.clear();
            return false;
        }
        value.emplace_back(std::move(v));
    }
    return true;
}

template<typename K, typename V>
bool DataStream::read(std::map<K, V> &value)
{
    value.clear();
    //检测缓冲区是否越界
    if(_pos >= _buffer.size())
    {
        std::cerr << "Error: Buffer overflow during deserialization.\n";
        return false;
    }
    if (_buffer[_pos] != DataType::MAP)
    {
        std::cout<<"unserialization is not map\n";
        return false;
    }
    _pos++; // 移动到下一个位置
    int len;
    if(!read(len))
    {
        std::cerr<<"Error:Failed to read map length\n";
        return false;
    }
    for (int i = 0; i < len; i++)
    {
        K k;
        if (!read(k))
        {
            std::cerr << "Error: Failed to read map key at index " << i << ".\n";
            value.clear(); // 清空已读取的部分数据
            return false;
        }

        V v;
        if (!read(v))
        {
            std::cerr << "Error: Failed to read map value at index " << i << ".\n";
            value.clear(); // 清空已读取的部分数据
            return false;
        }
        //使用移动语义减少拷贝开销
        value.emplace(std::move(k),std::move(v));
    }
    return true;
}

template<typename T>
bool DataStream::read(std::set<T> &value)
{
    value.clear();
    // 检测缓冲区是否越界
    if (_pos >= _buffer.size())
    {
        std::cerr << "Error: Buffer overflow during deserialization.\n";
        return false;
    }
    if(_buffer[_pos] != DataType::SET)
    {
        std::cout<<"unserialization is not set\n";
        return false;
    }
    _pos++;
    int len;
    if (!read(len))
    {
        std::cerr << "Error: Failed to read set length.\n";
        return false;
    }
    for(int i=0;i<len;i++)
    {
        T v;
        if (!read(v))
        {
            std::cerr << "Error: Failed to read set element at index " << i << ".\n";
            value.clear(); // 清空已读取的部分数据
            return false;
        }
        value.insert(std::move(v));
    }
    return true;
}

template<typename K, typename V>
bool DataStream::read(std::unordered_map<K, V> &value)
{
    value.clear();
    //检测缓冲区是否越界
    if(_pos >= _buffer.size())
    {
        std::cerr << "Error: Buffer overflow during deserialization.\n";
        return false;
    }
    if (_buffer[_pos] != DataType::UNORDEREDMAP)
    {
        std::cout<<"unserialization is not unordered_map\n";
        return false;
    }
    _pos++; // 移动到下一个位置
    int len;
    if(!read(len))
    {
        std::cerr<<"Error:Failed to read unordered_map length\n";
        return false;
    }
    for (int i = 0; i < len; i++)
    {
        K k;
        if (!read(k))
        {
            std::cerr << "Error: Failed to read unordered_map key at index " << i << ".\n";
            value.clear(); // 清空已读取的部分数据
            return false;
        }

        V v;
        if (!read(v))
        {
            std::cerr << "Error: Failed to read unordered_map value at index " << i << ".\n";
            value.clear(); // 清空已读取的部分数据
            return false;
        }
        //使用移动语义减少拷贝开销
        value.emplace(std::move(k),std::move(v));
    }
    return true;
}


template<typename T>
DataStream &DataStream::operator<<(const std::vector<T> &value)
{
    write(value);
    return *this;
}

template<typename T>
DataStream &DataStream::operator>>(std::vector<T> &value)
{
    read(value);
    return *this;
}

template<typename T>
DataStream &DataStream::operator<<(const std::list<T> &value)
{
    write(value);
    return *this;
}

template<typename T>
DataStream &DataStream::operator>>(std::list<T> &value)
{
    read(value);
    return *this;
}

template<typename K, typename V>
DataStream &DataStream::operator<<(const std::map<K, V> &value)
{
    write(value);
    return *this;
}

template<typename K, typename V>
DataStream &DataStream::operator>>(std::map<K, V> &value)
{
    read(value);
    return *this;
}

template<typename T>
DataStream &DataStream::operator<<(const std::set<T> &value)
{
    write(value);
    return *this;
}

template<typename T>
DataStream &DataStream::operator>>(std::set<T> &value)
{
    read(value);
    return *this;
}

template<typename K, typename V>
DataStream &DataStream::operator<<(const std::unordered_map<K, V> &value)
{
    write(value);
    return *this;
}

template<typename K, typename V>
DataStream &DataStream::operator>>(std::unordered_map<K, V> &value)
{
    read(value);
    return *this;
}

template<typename T, typename... Args>
void DataStream::write_args(const T &value, const Args &... args)
{
    write(value);
    write_args(args...);
}
template<typename T, typename... Args>
bool DataStream::read_args(T &value, Args &... args)
{
    read(value);
    read_args(args...);
    return true;
}



#endif //NETWORKCOMPONENT_DATASTREAM_H
